// connect.js
const POPUP_SCRIPT_MSG = 'popupScriptMsg';
const POPUP_SCRIPT_BG_MSG = 'popupScriptMsg-BG';
const CONTENT_SCRIPT_BG_MSG = 'contentMsg-BG';
export const PopupScript = {
  send({ type, data, cb }) {
    if (chrome && chrome.tabs && chrome.tabs.query && chrome.tabs.sendMessage) {
      chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
        chrome.tabs.sendMessage(tabs[0].id, { uri: POPUP_SCRIPT_MSG, type, data }, (res) => {
          cb && cb(res);
        });
      });
    }
  },

  sendBg({ type, data, cb }){
    if (chrome && chrome.tabs && chrome.tabs.query && chrome.tabs.sendMessage) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.sendMessage(tabs[0].id, { uri: POPUP_SCRIPT_BG_MSG, type, data }, (res) => {
            cb && cb(res);
          });
        });
      }
  },
};

const contentHanders = {};

export const ContentScript = {
  isInit: false,
  init() {
    if (chrome && chrome.runtime && chrome.runtime.onMessage && chrome.runtime.onMessage.addListener) {
      chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
        const { uri, data, type } = request;
        if (uri == POPUP_SCRIPT_MSG) {
          const cb = contentHanders[type];
          cb && cb(data, sendResponse);
        }
      });
    }
  },
  on(type, cb) {
    if (!this.isInit) {
      this.init();
    }
    contentHanders[type] = cb;
  },
  sendBg({ type, data, cb }){
    if (chrome && chrome.tabs && chrome.tabs.query && chrome.tabs.sendMessage) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.sendMessage(tabs[0].id, { uri: CONTENT_SCRIPT_BG_MSG, type, data }, (res) => {
            cb && cb(res);
          });
        });
      }
  }
};


const popcontentHanders = {};

export const BackgroundScript = {
  isInit: false,
  init() {
    if (chrome && chrome.runtime && chrome.runtime.onMessage && chrome.runtime.onMessage.addListener) {
      chrome.runtime.onMessage.addListener(async function (request, sender, sendResponse) {
        console.log('background___',request)
        const { uri, data, type } = request;
        if (uri == POPUP_SCRIPT_BG_MSG || uri == CONTENT_SCRIPT_BG_MSG) {
          const cb = popcontentHanders[type];
          cb && cb(data, sendResponse);
        }
      });
    }
  },
  on(type, cb) {
    if (!this.isInit) {
      this.init();
    }
    popcontentHanders[type] = cb;
  },
  sendContent({ type, data, cb }){
    if (chrome && chrome.tabs && chrome.tabs.query && chrome.tabs.sendMessage) {
        chrome.tabs.query({ active: true, currentWindow: true }, function (tabs) {
          chrome.tabs.sendMessage(tabs[0].id, { uri: CONTENT_SCRIPT_BG_MSG, type, data }, (res) => {
            cb && cb(res);
          });
        });
      }
  }
};